package org.smth.search.fetcher.impl;

import com.google.inject.Injector;

import org.smth.search.fetcher.FetcherManager;
import org.smth.search.fetcher.FetcherThread;

import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.Callable;

public class FetcherManagerImpl extends RunnableBase implements FetcherManager, Callable<Object> {

	private Injector injector;

	private int num;

	private List<FetcherThread> threads;

	public int getThreadNum() {
		return num;
	}

	public void setThreadNum(int num) {
		this.num = num;
	}

	public synchronized void startAll() {
		if (threads == null) {
			threads = new ArrayList<FetcherThread>();
		}
		for (int i = 0; i < num; i++) {
			FetcherThread thread = injector.getInstance(FetcherThread.class);
			thread.setInjector(injector);
			threads.add(thread);
		}
		for (int i = 0; i < num; i++) {
			threads.get(i).start();
		}
	}

	protected Callable<Object> createRunnable() {
		return this;
	}

	private long interval;

	public Object call() throws Exception {
		startAll();
		while (running) {
			for (FetcherThread thread : threads) {
				thread.start();
				if (!running) {
					break;
				}
			}
			Thread.sleep(interval);
		}
		return running;
	}

	public void startAllNoStop(long interval) {
		this.interval = interval;
		super.start();
	}

	public void stopAllNoStop() {
		super.stop();
	}

	public boolean isAllNoStop() {
		return super.isRunning();
	}

	public synchronized void stopAll() {
		for (int i = 0; i < num; i++) {
			threads.get(i).stop();
		}
	}

	public List<FetcherThread> getThreads() {
		return threads;
	}

	public void setInjector(Injector injector) {
		this.injector = injector;
	}

}
